package com.g.code.ebookssync.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.g.code.ebookssync.dao.BooksDao;
import com.g.code.ebookssync.pojo.EBook;
import com.g.code.ebookssync.pojo.EbookArchive;
import com.kuaipan.client.KuaipanAPI;
import com.kuaipan.client.ProgressListener;
import com.kuaipan.client.exception.KuaipanAuthExpiredException;
import com.kuaipan.client.exception.KuaipanIOException;
import com.kuaipan.client.exception.KuaipanServerException;
import com.kuaipan.client.hook.SleepyProgressListener;
import com.kuaipan.client.model.KuaipanFile;
import com.sina.sae.fetchurl.SaeFetchurl;
import com.sina.sae.storage.SaeStorage;
import com.sina.sae.storage.StorageUtil;


@Service
public class UploadService {
    
    private static Log log = LogFactory.getLog(UploadService.class);
    
    @Autowired
    private BooksDao booksDao;
    
    public int uploadFile(String bookId, KuaipanAPI api) {
        EBook book = booksDao.getEbookById(bookId);
        
        KuaipanFile path = null;
        // 验证目录是否已经创建
        String rootPath = "/" + book.getName();
        try {
            path = api.metadata(rootPath, true);
        } catch (KuaipanIOException e) {
            log.error(e.getMessage(), e);
        } catch (KuaipanServerException e) {
            try {
                // 不存着目录，创建
                api.createFolder(rootPath);
                path = api.metadata(rootPath, true);
            } catch (KuaipanIOException e1) {
                log.error(e1.getMessage(), e1);
            } catch (KuaipanServerException e1) {
                log.error(e1.getMessage(), e1);
            } catch (KuaipanAuthExpiredException e1) {
                log.error(e1.getMessage(), e1);
            }
        } catch (KuaipanAuthExpiredException e) {
            log.error(e.getMessage(), e);
        }
        
        Map<String, KuaipanFile> kfiles = new HashMap<String, KuaipanFile>();
        for(KuaipanFile f : path.files) {
            kfiles.put(f.name, f);
        }
        
        List<EbookArchive> archives = booksDao.getArchivesByBookId(bookId);
        
        SaeStorage storage = new SaeStorage("w0xlymnzz5","0ikmkm5hm2m1x5j2jk32300h2y15h2h4hjmlx2wh", "ebookssync");
        
        
        for (EbookArchive archive : archives) {
            KuaipanFile kf = kfiles.get(archive.getFile_name());
            if (kf != null && kf.size == archive.getFile_size()) {
//                storage.write("ebookssync", archive.getFile_location() + "existinkuiapan.debug", "1");
                continue;
            }
            // test 
//            storage.write("ebookssync", archive.getFile_location() + 1, "1");
            
            if (!storage.fileExists("ebookssync", archive.getFile_location())) {
//                storage.write("ebookssync", archive.getFile_location() + "notexist.debug", "1");
                continue;
            }
            byte[] ebookContext = storage.read("ebookssync", archive.getFile_location());
//            if (ebookContext.length != archive.getFile_size()) {
//                storage.write("ebookssync", archive.getFile_location() + "length" + ebookContext.length + ".debug", "1");
//            }
            InputStream is = new ByteArrayInputStream(ebookContext);
            try {
                api.uploadFile(rootPath + "/" + archive.getFile_name(), is, ebookContext.length, true, null);
            } catch (KuaipanIOException e1) {
                log.error(e1.getMessage(), e1);
            } catch (KuaipanServerException e1) {
                log.error(e1.getMessage(), e1);
            } catch (KuaipanAuthExpiredException e1) {
                log.error(e1.getMessage(), e1);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        
        return 0;
    }
    
    
    
    public void uploadFile(String bookId, String userId) {
        
    }
    
    public static void main(String[] args) {
        SaeStorage storage = new SaeStorage("w0xlymnzz5","0ikmkm5hm2m1x5j2jk32300h2y15h2h4hjmlx2wh", "ebookssync");
        
        storage.write("ebookssync", "InfoQ-Architect/test.txt", "112");
//        System.out.println(storage.fileExists("ebookssync", "InfoQ-Architect/Architect-201211-by-InfoQ.pdf"));
    }
    
}
